import pdfplumber
import requests
import json
import os
from rich.progress import track
import os
import win32com.client as win32
from docx import Document

def productInsureInformation(path:str):
     file = os.path.basename(path)
     if file.endswith('.pdf'):
        return file.split('.')[0]
     else:
        return "default"

def pdfToPng(file_path):
    with pdfplumber.open(file_path) as pdf:
        fileName = os.path.basename(file_path)
        filesPath = productInsureInformation(file_path)
        newFileDir = file_path.replace(fileName,'')+'/'+filesPath
        if not os.path.exists(newFileDir):
            os.makedirs(newFileDir)
        for i, page in enumerate(pdf.pages):
            im = page.to_image(resolution=360)
            im.save(r'{}\page-{}.png'.format(newFileDir,i + 1),"png")
    return newFileDir

def uploadImage(filePath:str):
    urls = []
    file_list = os.listdir(filePath)
    for file in (file_list):
        if file.endswith('.png'):
            with open('{}'.format(filePath+'/'+file),'rb') as file:
                content=file.read()
            url = "https://nbims.haiziwang.com/upload/stream.do?bucket=hzwimspic-1251601690&bizCode=fin_file_kos&appCode=fin-file"
            payload = content
            headers = {
            'kosToken': 'OKAOMG8NLXoL98Rv0TPNr1Ahb+0vcT9mpCt8JGM3xWqE1ElXTrz759fCn3cw2TwLrMilydRfalJocZNC8TdPIYF9SPfiPrD25Z8oVHzY1gl4tXLgTRP2r7NCPnFqI8/h6vCrbRGpcveD0OPS8uqWg36jPsKeIghGJEcvVSw6BT0=',
            'Content-Type': 'image/png'
            }
            response = requests.request("POST", url, headers=headers, data=payload)
            data=json.loads(response.text)
            url=data.get('content').get('downloadUrl')
            urls.append(url)
    return urls


def gengerateHtml(filePath):
    urls = uploadImage(filePath)
    imgs = ''
    for url in urls:
        informationCode = '<img src="{}" alt="" />'.format(url)
        imgs+=informationCode
    allCode = '<p>{}</p>'.format(imgs)
    with open(filePath+"/"+'image.html','w+') as file:
        file.write(allCode)

def convert_to_pdf(input_path, output_path):
    # 创建Word应用程序实例
    word_app = win32.gencache.EnsureDispatch('Word.Application')
    # 设置应用程序可见性为False（不显示Word界面）
    word_app.Visible = False

    try:
        # 打开Word文档
        doc = word_app.Documents.Open(input_path)
        # 保存为PDF
        doc.SaveAs(output_path, FileFormat=17)
        doc.Close()
        return True
    except Exception as e:
        print("转换失败：" + str(e))
        return False
    finally:
        # 关闭Word应用程序
        word_app.Quit()
